package com.brzjomo.jomosadventure.item;

import com.brzjomo.jomosadventure.JomosAdventure;
import com.brzjomo.jomosadventure.init.ModItems;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Formatting;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class TimingTeleportGem extends Item {
    public int time;
    private NbtCompound compoundTag = new NbtCompound();
    private boolean isUsed = true;

    //调试用
    private static int timec = 0;

    public TimingTeleportGem(int time, Settings settings) {
        super(settings);
        this.time = time;
    }

    @Override
    public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
        if (!world.isClient()) {
            writePositionToTag(compoundTag, user.getBlockPos());
            writeDimensionToTag(compoundTag, world.getDimension());

            isUsed = false;

            //damage item
            if (!world.isClient) {
                if (user != null){
                    JomosAdventure.LOGGER.info("should damage 1");
                    user.getStackInHand(Hand.MAIN_HAND).damage(1, user, (p) -> {
                        p.sendToolBreakStatus(user.getActiveHand());
                        //p.sendEquipmentBreakStatus(EquipmentSlot.MAINHAND);
                    });
                }
            }

            //调试用
            JomosAdventure.LOGGER.info("isUesed: " + isUsed);
            JomosAdventure.LOGGER.info("isUesed: " + compoundTag.toString());

            user.sendMessage(new TranslatableText("item." + JomosAdventure.MOD_ID + "." + "timing_teleport_gem" + ".message." + "1"), false);
        }
        return super.use(world, user, hand);
    }

    public void writePositionToTag(NbtCompound tag, BlockPos pos) {
        tag.putInt("PinedPos_X", pos.getX());
        tag.putInt("PinedPos_Y", pos.getY());
        tag.putInt("PinedPos_Z", pos.getZ());
    }

    public BlockPos readPositionFromTag(NbtCompound tag) {
        return new BlockPos(tag.getInt("PinedPos_X"), tag.getInt("PinedPos_Y"), tag.getInt("PinedPos_Z"));
    }

    public void writeDimensionToTag(NbtCompound tag, DimensionType dimension) {
        tag.putString("PinedDimension", dimension.toString());
    }

    //目前无法判断所处维度是否一致
    public Boolean isSameDimension(NbtCompound tag, DimensionType dimension) {
//        return tag.getString("PinedDimension").equals(dimension.toString());
        return true;
    }

    //用户打开背包后，newTag才必定刷新
    @Override
    public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
        //只要宝石在身上，不用放在主手就可以得到提示。但身上有多个宝石的情况下，提示文本会重复显示
        if (!world.isClient()) {
            if (world.getTimeOfDay() == time - 20 * 15) {
                world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("item." + JomosAdventure.MOD_ID + "." + "timing_teleport_gem" + ".message." + "2"), false);
            }

            if (world.getTimeOfDay() == time - 20 * 8) {
                world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("item." + JomosAdventure.MOD_ID + "." + "timing_teleport_gem" + ".message." + "3"), false);
                world.playSound((PlayerEntity)null, entity.getX(), entity.getY(), entity.getZ(), SoundEvents.BLOCK_PORTAL_TRIGGER, SoundCategory.NEUTRAL, 0.2F, 0.4F / (world.getRandom().nextFloat() * 0.4F + 0.8F));
            }

            if (world.getTimeOfDay() == time - 20 * 5) {
                world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("5"), false);
            }

            if (world.getTimeOfDay() == time - 20 * 4) {
                world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("4"), false);
            }

            if (world.getTimeOfDay() == time - 20 * 3) {
                world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("3"), false);
            }

            if (world.getTimeOfDay() == time - 20 * 2) {
                world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("2"), false);
            }

            if (world.getTimeOfDay() == time - 20) {
                world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("1"), false);
            }

        }

        if (stack.isItemEqual(new ItemStack(ModItems.TIMING_TELEPORT_GEM)) && selected || stack.isItemEqual(new ItemStack(ModItems.NIGHTFALL_TELEPORT_GEM)) && selected) {
            NbtCompound newTag = stack.getOrCreateNbt();

            if (!isUsed) {
                newTag.copyFrom(compoundTag);
                isUsed = true;

                //调试用
                JomosAdventure.LOGGER.info("Copyed: " + isUsed);
                JomosAdventure.LOGGER.info("Copyed: " + newTag.toString());
            }

            //调试用
            timec++;
            if (timec % 300 == 0) {
                JomosAdventure.LOGGER.info("Logger:" + isUsed);
                JomosAdventure.LOGGER.info("Logger: " + newTag.toString());
            }

            if (!world.isClient() && newTag.contains("PinedPos_X") && isSameDimension(newTag, world.getDimension())) {
                if (world.getTimeOfDay() == time) {
                    BlockPos pinnedPosition = readPositionFromTag(newTag);

                    //调试用
                    JomosAdventure.LOGGER.info("尝试传送的地点:" + pinnedPosition.toString());

                    world.playSound((PlayerEntity)null, entity.getX(), entity.getY(), entity.getZ(), SoundEvents.BLOCK_END_PORTAL_SPAWN, SoundCategory.NEUTRAL, 0.5F, 0.4F / (world.getRandom().nextFloat() * 0.4F + 0.8F));

                    entity.requestTeleport(pinnedPosition.getX(), pinnedPosition.getY(), pinnedPosition.getZ());
                    world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("item." + JomosAdventure.MOD_ID + "." + "timing_teleport_gem" + ".message." + "4"), false);
                }
            }

            if (!world.isClient() && !newTag.contains("PinedPos_X")) {
                if (selected && world.getTimeOfDay() == time) {
                    world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("item." + JomosAdventure.MOD_ID + "." + "timing_teleport_gem" + ".error." + "1"), false);
                }
            }

            if (!world.isClient() && newTag.contains("PinedPos_X") && !isSameDimension(newTag, world.getDimension())) {
                if (selected && world.getTimeOfDay() == time) {
                    world.getClosestPlayer(entity, 1).sendMessage(new TranslatableText("item." + JomosAdventure.MOD_ID + "." + "timing_teleport_gem" + ".error." + "2"), false);
                }
            }
        }

        super.inventoryTick(stack, world, entity, slot, selected);
    }

    @Override
    public void appendTooltip(ItemStack stack, @Nullable World world, List<Text> tooltip, TooltipContext context) {
        tooltip.add(new TranslatableText(stack.getTranslationKey() + ".tooltip." + "1").formatted(Formatting.DARK_AQUA).formatted(Formatting.ITALIC));
        tooltip.add(new TranslatableText(stack.getTranslationKey() + ".tooltip." + "2").formatted(Formatting.DARK_GRAY));
    }
}
